import { defineStore } from 'pinia'
import authApi from '@/api/auth'


// 增强版安全JSON解析
function safeParseJson(jsonString) {
  // 处理 undefined/null/空字符串
  if (!jsonString || jsonString === 'undefined' || jsonString === 'null') {
    return null
  }
  try {
    return JSON.parse(jsonString)
  } catch (e) {
    console.error('JSON解析错误:', e)
    return null
  }
}

// 安全读取localStorage
function getLocalStorage(key) {
  try {
    return localStorage.getItem(key)
  } catch (e) {
    console.error('访问localStorage失败:', e)
    return null
  }
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    ...getLockState(),
    token: getLocalStorage('token') || '',
    user: safeParseJson(getLocalStorage('user')) || null,  // 确保最终为null
    LOCK_THRESHOLD: 5,
    LOCK_DURATION: 30 * 60 * 1000,
    initialized: false
  }),
  getters: {
    isLocked(state) {
      if (state.lockStartTime === 0) return false
      return Date.now() - state.lockStartTime < state.LOCK_DURATION
    },
    remainingLockTime(state) {
      if (!this.isLocked) return 0
      return state.LOCK_DURATION - (Date.now() - state.lockStartTime)
    },
    isLoggedIn(state) {
      return !!state.token && !!state.user
    },
    currentUser: (state) => state.user
  },
  actions: {
    initAuth() {
      if (this.initialized) return
      this.initialized = true
      this.checkLockStatus()
    },

    setAuthData({ user, token }) {
      this.user = user
      this.token = token
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('token', token)
    },

    clearAuthData() {
      this.token = ''
      this.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },


    saveLockState() {
      localStorage.setItem('lockState', JSON.stringify({
        failCount: this.failCount,
        lockStartTime: this.lockStartTime
      }))
    },

    incrementFailCount() {
      this.failCount++
      if (this.failCount >= this.LOCK_THRESHOLD) {
        this.lockStartTime = Date.now()
      }
      this.saveLockState()
    },

    resetFailCount() {
      this.failCount = 0
      this.lockStartTime = 0
      this.saveLockState()
    },

    checkLockStatus() {
      if (this.isLocked && Date.now() - this.lockStartTime >= this.LOCK_DURATION) {
        this.resetFailCount()
      }
    },

    async login(credentials) {
      this.initAuth()
      console.log(credentials.Username);
      console.log(credentials.Password);


      if (this.isLocked) {
        const minutes = Math.ceil(this.remainingLockTime / (60 * 1000))
        throw new Error(`登录失败次数过多，账户已锁定${minutes}分钟`)
      }

      try {
        const user = await authApi.login({
          Username: credentials.Username,
          Username: credentials.Password,
        })
        console.log();

        localStorage.setItem('user', JSON.stringify(this.user))
        return this.user

      } catch (error) {
        this.incrementFailCount()
        throw error
      }
    },

    async logout() {
      try {
        this.user = null
        this.token = ''
        localStorage.removeItem('user')
        localStorage.removeItem('token')
      } finally {
        this.clearAuthData()
      }
    },

    // 新增：获取用户信息
    async fetchUserInfo() {
      const response = await authApi.getUserInfo()
      if (response.code === 200) {
        this.user = {
          ...this.user,
          ...response.userInfo
        }
        localStorage.setItem('user', JSON.stringify(this.user))
        return this.user
      }
      throw new Error(response.msg || '获取用户信息失败')
    }
  }
})

// 从localStorage恢复锁定状态
function getLockState() {
  const state = getLocalStorage('lockState')
  return safeParseJson(state) || {
    failCount: 0,
    lockStartTime: 0
  }
}